<template>
  <el-row :gutter="20" class="page-container">
    <!-- 车次信息卡片 -->
    <el-col :span="24">
      <el-card class="dashboard-card">
        <div class="card-header">
          <div class="card-title">今日热搜</div>
        </div>

        <!-- 表头 -->
        <div class="table-header">
          <el-row class="header-row">
            <el-col :span="2" class="header-cell">
              <span style="text-align: center; width: 100%">编号</span>
            </el-col>
            <el-col :span="8" class="header-cell">
              <span style="text-align: center; width: 100%">热搜名称</span>
            </el-col>
            <el-col :span="2" class="header-cell">
              <span style="text-align: center; width: 100%">热搜排名</span>
            </el-col>
            <el-col :span="2" class="header-cell">
              <span style="text-align: center; width: 100%">热度值</span>
            </el-col>
            <el-col :span="8" class="header-cell">
              <span style="text-align: center; width: 100%">出现时间</span>
            </el-col>
            <el-col :span="2" class="header-cell">
              <span style="text-align: center; width: 100%">平台</span>
            </el-col>
          </el-row>
        </div>

        <!-- 滚动区域 -->
        <vue3-scroll-seamless
            class="seamless-scroller"
            :class-options="scrollOptions"
            :data-list="list"
        >
          <!-- 数据行 -->
          <template v-if="list.length > 0">
            <el-row
                v-for="(item, index) in list"
                :key="index"
                class="data-row"
            >
              <el-col :span="2" class="data-cell">
                <span style="text-align: center; width: 100%;">{{ item.id }}</span>
              </el-col>
              <el-col :span="8" class="data-cell">
                <span style="text-align: center; width: 100%;">{{ item.hotTitle }}</span>
              </el-col>
              <el-col :span="2" class="data-cell">
                <span style="text-align: center; width: 100%;">{{ item.hotRank }}</span>
              </el-col>
              <el-col :span="2" class="data-cell">
                <span style="text-align: center; width: 100%;">{{ item.hotFever }}</span>
              </el-col>
              <el-col :span="8" class="data-cell">
                <span style="text-align: center; width: 100%;">{{ item.hotTime }}</span>
              </el-col>
              <el-col :span="2" class="data-cell">
                <span style="text-align: center; width: 100%;">{{ item.hotPlatform }}</span>
              </el-col>
            </el-row>
          </template>

          <!-- 空状态 -->
          <div v-else class="empty-state">
            <el-empty description="暂无记录" />
          </div>
        </vue3-scroll-seamless>
      </el-card>
    </el-col>

    <!-- 其他信息卡片（示例） -->
    <el-col :span="12">
      <el-card class="dashboard-card">
        <div class="card-header">
          <div class="card-title">热度排名（微博）</div>
        </div>
        <div class="chart-wrapper">
          <div id="barChart" class="chart-container"></div>
        </div>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card class="dashboard-card">
        <div class="card-header">
          <div class="card-title">昨日词云</div>
        </div>
        <div v-show="cloudData.length > 0" ref="chartContainer" class="wordcloud-wrapper"></div>
        <el-empty
            v-show="!(cloudData.length > 0)"
            description="暂无词云数据"
            class="wordcloud-wrapper"
        />
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import {computed, nextTick, onBeforeUnmount, onMounted, reactive, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import moment from "moment";
import * as echarts from "echarts"
import type { ECharts, EChartsOption } from 'echarts'
import 'echarts-wordcloud'

onMounted(() => {
  getScrollList()
  getCloudData()
  initChart()
})

onBeforeUnmount(() => {
  // 清理图表实例
  chartInstance?.dispose()
  chartInstance = null
})

interface HotSearchItem {
  id: number;
  hotFever: string;
  hotPlatform: string;
  hotRank: string;
  hotTime: string;
  hotTitle: string;
}

const list = ref<HotSearchItem[]>([]);

const getDate = () => {
  return moment().subtract(1, 'day').format('YYYY-MM-DD')
  // return moment().format('YYYY-MM-DD')
  // return '2025-04-24'
}

// 获取滚动列表
const getScrollList = () => {
  axios.get(window.BASE_URL + '/api/hotSearch/getLatestHotData').then(res => {
    // console.log(res);
    if (res.data.flag) {
      list.value = res.data.data.map((item: any, index: number) => {
        return {
          id: index + 1,
          hotFever: item.hotFever,
          hotPlatform: item.hotPlatform,
          hotRank: item.hotRank,
          hotTime: item.hotTime,
          hotTitle: item.hotTitle
        }
      })
      nextTick(initChart)  // DOM 更新后初始化图表
      getBarData()
      // console.log(list)
    } else {
      ElMessage.error(res.data.msg)
      destroyChart()  // 强制销毁图表
    }
  }).catch(() => {
    cloudData.value = []
    destroyChart()
  })
}

// 销毁方法
const destroyChart = () => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
}

const scrollOptions = reactive({
  direction: 1,       // 向上滚动
  step: 0.5,           // 滚动速度
  hoverStop: true,     // 悬停暂停
  singleHeight: 30,    // 单行高度
  waitTime: 2000,      // 启动延迟
  limitMoveNum: 8      // 最少滚动项
});

// 词云设定
const chartContainer = ref<HTMLElement | null>(null)
let chartInstance: ECharts | null = null

const cloudData = ref<{ name: string; value: number }[]>([])

const getCloudData = () => {
  axios.get(window.BASE_URL + '/api/hotSearch/getAnalysis/' + getDate()).then(res => {
    // console.log(res);
    if (res.data.flag) {
      cloudData.value = res.data.data.keywords
      // console.log(cloudData.value)
      updateChart()
    } else {
      ElMessage.error(`词云：${res.data.msg}`)
    }
  })
}

const initChart = () => {
  // 确保 DOM 元素已挂载
  if (!chartContainer.value) return

  // 清理旧实例（防止重复创建）
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }

  try {
    // 初始化 ECharts 实例
    chartInstance = echarts.init(chartContainer.value)

    // ---------- 图表配置项 ----------
    const option: EChartsOption = {
      series: [{
        type: 'wordCloud',  // 指定为词云类型
        data: cloudData.value,  // 绑定响应式数据
        shape: 'pentagon',  // 形状：circle | cardioid | diamond 等

        // center: ['50%', '30%'],
        // ---------- 文字样式配置 ----------
        textStyle: {
          fontFamily: 'sans-serif',  // 字体
          fontWeight: 'bold',        // 加粗
          // 随机颜色生成函数
          color: () => {
            return `rgb(${[
              Math.round(Math.random() * 160),  // R 通道 (0-160)
              Math.round(Math.random() * 160),  // G 通道
              Math.round(Math.random() * 160)   // B 通道
            ].join(',')})`
          }
        },

        // ---------- 高亮样式配置 ----------
        emphasis: {
          focus: 'none',  // 高亮聚焦模式：'self' 只高亮当前词
          textStyle: {
            textShadowBlur: 5,           // 阴影模糊度
            textShadowColor: '#222',      // 阴影颜色
          }
        },

        // ---------- 其他布局参数 ----------
        gridSize: 10,          // 网格大小，决定词间距
        sizeRange: [12, 60],   // 字体大小范围 [最小, 最大]
        rotationRange: [-90, 90], // 旋转角度范围
        rotationStep: 90,      // 旋转角度步进值
        width: '90%',                 // 限制最大宽度
        height: '90%',                // 限制最大高度
      }]
    }

    // 应用配置到图表实例
    chartInstance.setOption(option)
  } catch (error) {
    console.error('图表初始化失败:', error)
  }
}

// 更新词云数据
const updateChart = () => {
  if (!chartInstance) return

  const newOption: EChartsOption = {
    series: [{
      type: 'wordCloud',
      data: cloudData.value // 使用最新数据
    }]
  }

  chartInstance.setOption(newOption)
}

// 柱状图内容
const xAxisData = ref(['A', 'B', 'C', 'D', 'E', 'F', 'G'])
const yAxisData = ref([10, 20, 30, 40, 50, 60, 70])

// 柱状图配置
const barChartOption = computed(() => ({
  tooltip: { // 新增 tooltip 配置
    trigger: 'item',       // 触发方式：数据项
    backgroundColor: '#333',
    borderColor: '#666',
    textStyle: {
      color: '#fff',
      fontSize: 14
    },
    // 自定义提示内容
    formatter: (params: any) => {
      return `
        <div style="margin:5px">
          <div style="font-size:16px;font-weight:bold;color:#409EFF">
            ${params.name}
          </div>
          <div style="margin-top:8px">
            <span style="display:inline-block;width:60px">热度值：</span>
            <span style="color:#ffd700">${params.value}</span>
          </div>
        </div>
      `;
    }
  },
  grid: {
    top: '5%',    // 顶部留空比例
    bottom: '25%', // 底部留空比例
    // containLabel: true // 包含坐标轴标签
  },
  xAxis: {
    type: 'category',
    data: xAxisData.value,
    axisLabel: {
      // 截断文本并添加省略号
      formatter: (value: string) => {
        const maxLength = 6 // 最大显示字符数（根据实际宽度调整）
        return value.length > maxLength
            ? `${value.substring(0, maxLength)}...`
            : value
      },
      rotate: 45,          // 倾斜45度防止重叠
      interval: 0,          // 强制显示所有标签
      textStyle: {
        color: '#666',
        fontSize: 12
      }
    }
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: yAxisData.value,
      type: 'bar',
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      },
    }
  ]
}));

let barChart: ECharts | null = null;

// 初始化柱状图
const updateBarChart = () => {
  // 销毁旧实例
  if (barChart) {
    barChart.dispose();
    barChart = null;
  }

  // 创建新实例
  const chartDom = document.getElementById('barChart');
  if (!chartDom) return;

  barChart = echarts.init(chartDom);
  barChart.setOption(barChartOption.value);
}

// 数据存储方式（原 yAxisData 改造为对象数组）
const barData = ref<Array<{
  name: string;
  value: number;
  platform: string;
  time: string;
}>>([]);

// 获得柱状图数据
const getBarData = () => {
  barData.value = [];

  // 按照 hotFever 值降序排序并截取前十个数据项
  const sortedList = list.value
      .filter(item => item.hotPlatform === 'weibo') // 筛选出平台为微博的数据
      .filter(item => item.hotRank !== '0')
      .sort((a, b) => Number(b.hotFever) - Number(a.hotFever)) // 按照 hotFever 降序排序
      .slice(0, 10); // 截取前十个数据项

  sortedList.forEach(item => {
    barData.value.push({
      name: item.hotTitle,
      value: Number(item.hotFever),
      platform: item.hotPlatform,
      time: item.hotTime
    });
  });

  xAxisData.value = barData.value.map(v => v.name);
  yAxisData.value = barData.value.map(v => v.value);
  nextTick(updateBarChart);
}
</script>

<style scoped lang="scss">
.page-container {
  padding: 20px;
  background: #f5f7fa;
}

.dashboard-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

  :deep(.el-card__body) {
    padding: 0;
  }
}

.card-header {
  padding: 18px 24px;
  border-bottom: 1px solid #ebeef5;

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.table-header {
  padding: 0 24px;
  background: #f8f9fc;

  .header-row {
    height: 48px;

    .header-cell {
      display: flex;
      align-items: center;
      font-weight: 500;
      color: #606266;
    }
  }
}

.seamless-scroller {
  height: 240px;
  overflow: hidden;

  .data-row {
    padding: 0 24px;
    height: 30px;
    transition: background 0.3s;

    &:hover {
      background: #f5f7fa;
    }

    &:not(:last-child) {
      border-bottom: 1px solid #ebeef5;
    }

    .data-cell {
      display: flex;
      align-items: center;
      color: #606266;
      font-size: 14px;

      &:not(:last-child) {
        border-right: 1px solid #ebeef5;
      }
    }
  }
}

.empty-state {
  height: 420px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.wordcloud-wrapper {
  height: 36vh;    /* 必须指定高度 */
  width: 100%;      /* 宽度自适应容器 */
  min-width: 300px; /* 最小宽度保证显示 */
  background: #fff; /* 建议设置背景色 */
  //border: 1px solid red;
  /* 可选：添加过渡效果 */
  //transition: height 0.3s ease;
}

.chart-container {
  width: 40vw;             // 保持原有宽度设置
  height: 36vh;            // 保持原有高度设置
  margin: 0 auto;          // 水平居中
  position: relative;      // 为子元素绝对定位提供基准
  // border: 1px solid red;
}

.chart-wrapper {
  width: 100%;
  height: 100%;
  display: flex;           // 启用弹性布局
  justify-content: center; // 水平居中
  align-items: center;     // 垂直居中
}
</style>